package com.mgg.message.service.notify.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mgg.common.enums.MessageNotifyEnum;
import com.mgg.common.dao.DaoSupport;
import com.mgg.message.service.notify.NotifyService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;

@Service("notifyService")
public class NotifyServiceImpl implements NotifyService {

	Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private DaoSupport dao;
	
	@Override
	public Integer getUnReadNotifyCount(String userId) throws Exception {
		return (Integer) dao.findForObject("NotifyMapper.getUnReadNotifyCount", userId);
	}
	
	@Override
	public List<Map<String, Object>> listNotifyIndex(String userId) throws Exception {
		List<Map<String, Object>> list = dao.findForList("NotifyMapper.listNotifyIndex", userId);
		return list;
	}

	@Override
	public List<Map<String, Object>> listNotifyByUserIdAndType(String userId, String msgType, Pageable page)
			throws Exception {
		PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		Map<String,String> queryMap = new HashMap<>();
		queryMap.put("userId", userId);
		queryMap.put("msgType", msgType);
		List<Map<String, Object>> notifyList = dao.findForList("NotifyMapper.listNotifyByUserIdAndType", queryMap);
		for (Map<String, Object> notify : notifyList) {
			if (0 == (Integer)notify.get("is_read")) {
				dao.update("NotifyMapper.updateNotifyRead", (Integer)notify.get("id"));
			}
		}
		return notifyList;
	}

	@Override
	public void send(MessageNotifyEnum messageNotifyEnum, String userId, Map<String,String> paramMap) throws Exception {
		try {
			Map<String,Integer> queryMap = new HashMap<>();
			queryMap.put("msg_type", messageNotifyEnum.getMsgType());
			queryMap.put("id", messageNotifyEnum.getTemplateId());
			Map<String,Object> templateMap = dao.findForObject("NotifyMapper.getMessageTemplateByTypeAndId", queryMap);
			if (MapUtils.isEmpty(templateMap)) {
				return;
			}
			
			if (MapUtils.isNotEmpty(paramMap)) {
				String content = (String) templateMap.get("content");			
				for (String key : paramMap.keySet()) {
					content = content.replace("${" + key + "}", paramMap.get(key));
				}
				templateMap.put("content", content);
			}
			templateMap.put("user_id", userId);
			dao.save("NotifyMapper.insertMessageNotify", templateMap);
		} catch(Exception e) {
			log.error("短信发送失败，exception = {}",e);
		}
	}
}
